package com.custom.action.core.methods.select;

import com.custom.action.core.TableInfoCache;
import com.custom.action.core.methods.MethodKind;
import com.custom.action.dbaction.AbstractSqlBuilder;
import com.custom.action.joiner.JoinConditionWrapper;
import com.custom.jdbc.executebody.BaseSqlExecutorBody;
import com.custom.jdbc.executebody.ExecuteBodyHelper;
import com.custom.jdbc.interfaces.CustomSqlSession;
import com.custom.jdbc.session.JdbcSqlSessionFactory;

/**
 * @author Xiao-Bai
 * @since 2023/5/17 23:03
 */
@SuppressWarnings("unchecked")
public class SelectListJoinByWrapperAsMappedType extends SelectListJoinByWrapper {

    @Override
    protected <T> CustomSqlSession createSqlSession(JdbcSqlSessionFactory sqlSessionFactory, Class<T> target, Object[] params) throws Exception {
        JoinConditionWrapper<T> wrapper = (JoinConditionWrapper<T>) params[1];
        String selectSql = joinWrapperTargetSql(sqlSessionFactory, wrapper, wrapper.getEntityClass());
        BaseSqlExecutorBody executorBody = ExecuteBodyHelper.createSelectIf(
                target, selectSql, sqlPrintSupport,
                wrapper.getParamValues().toArray()
        );
        if (TableInfoCache.hasTable(target)) {
            AbstractSqlBuilder<T> sqlBuilder = TableInfoCache.getSelectSqlBuilderCache(target, sqlSessionFactory);
            executorBody.setFieldTypeHandlerMap(sqlBuilder.getFieldTypeHandlerMap());
        }
        return sqlSessionFactory.createSqlSession(executorBody);
    }


    @Override
    public MethodKind getKind() {
        return MethodKind.SELECT_LIST_JOIN_BY_WRAPPER_AS_MAPPED_TYPE;
    }
}
